<?php
/**
 * Created by PhpStorm.
 * User: yafex
 * Date: 2021/5/12
 * Time: 14:40
 */
class ctrl_wish_pb extends L {

    /**
     * 描述 ：PB统计页面展示
     * 作者 ：Zoro.Zhu
     **/
    public function index(){
        $this->view->_pagingHtml = $this->paging();
        $this->view->headTitle = 'PB广告统计';
        $this->view->pbState = model_com::getVsConfig('pbState');
        $this->view->accountList = model_com::getAccount('wish');
        $this->display('/html/wish/pb.html');
    }

    /**
     * 描述 : 获取分页
     * 作者 : Zoro.Zhu
     */
    public function &paging($params = array()){
        $sql = model_pb::searchSql($params);
        $config = array(
            '广告名称<br>广告ID' => array(
                '_attr' => array(
                    'body' => '{`campaign_name`}<br>{`id`}',
                    'sort' => 'campaign_name'
                )
            ),
            '店铺名称<br>状态' => array(
                '_attr' => array(
                    'body' => '{`account`}<br>{`state`}',
                    'sort' => 'state'
                )
            ),
            'IB' => '{`intense_boost`}',
            '预算<br>花费' => '{`merchant_budget`}<br>{`total_campaign_spend`}',
            '总流量<br><font color="red">竞争值</font>' => '{`total_impressions`}<br><font color="red">{`competition`}</font>',
            '销量<br>销售额<br><font color="red">花费成交比</font>' => '{`sales`}<br>{`gmv`}<br><font color="red">{`transaction`}</font>',
            '更新时间<br>开始时间<br>结束时间' => array(
                '_attr' => array(
                    'body' => '{`updated_at`}<br>{`start_at`}<br>{`end_at`}',
                    'sort' => 'updated_at'
                )
            ),
            '产品ID<br>SPU<br>PB关键词' => ['_attr' => ['body' => ['html' => '{`product_id`}<br>{`parentSku`}<br>{`keyword`}'], 'attr' => 'style="width: 400px"']],
            '主图' => '<img src="{`image`}" style="width: 90px;height: 90px;display:block;" />',
            '数据统计时间' => '{`minDate`}<br>{`maxDate`}',
            '曝光量<br>浏览量<br>购买量' => '{`feed_impression`}<br>{`impressions`}<br>{`num_sold`}',
            '<font color="red">曝光浏览比<br>浏览购买比</font>' => '<font color="red">{`mainMap`}<br>{`buy`}</font>',
            '已出账订单数量<br>平均订单利润<br><font color="red">去广告费利润</font>' => '{`orderQty`}<br>{`orderGross`}<br><font color="red">{`pbGross`}</font>',
            '_attr' => array(
                "attr" => array (
                    "table" => 'id=pbList class="table table-hover table-condensed table-striped table-scroll jsHoverDetails textC"',
                    "btr" => "align='center' class='of-paging_item_odd tr_{`id`}'",
                ),
                'data' => &$sql,
                'params' => &$params,
                'call' => array($this, 'asCall'),
                'method' => __METHOD__,
                'save' => 'auto',
                'empty' => '查无此数据'
            )
        );
        return $this->_com->paging($config);
    }

    /**
     * 描述 : 整理数据
     * 作者 : Zoro.Zhu
     */
    public function asCall(&$data){
        $pbState = model_com::getVsConfig('pbState');
        foreach($data['data'] as &$val){
            $pbInfo = json_decode($val['pbData'], true);
            $val['state'] = $pbState[$pbInfo['state']]; //广告状态
            $val['merchant_budget'] = $pbInfo['merchant_budget']['currency_code'] . ' ' . $pbInfo['merchant_budget']['amount']; // 预算
            $val['total_campaign_spend'] = $pbInfo['total_campaign_spend']['currency_code'] . ' ' . $pbInfo['total_campaign_spend']['amount']; // 总花费
            $val['gmv'] = $pbInfo['gmv']['currency_code'] . ' ' . $pbInfo['gmv']['amount']; // 销售额
            $val['transaction'] = !empty($pbInfo['gmv']['amount']) && !empty($pbInfo['total_campaign_spend']['amount']) ? round($pbInfo['total_campaign_spend']['amount'] / $pbInfo['gmv']['amount'] * 100, 2) . '%' : '-';
            $val['sales'] = $pbInfo['sales']; //销量
            $val['type'] = $pbInfo['type']; // 广告类型
            $val['intense_boost'] = $pbInfo['intense_boost'] == 'true' ? '是' : '否';
            $val['updated_at'] = substr($pbInfo['updated_at'], 0, 10);
            $val['start_at'] = substr($pbInfo['start_at'], 0, 10);
            $val['end_at'] = substr($pbInfo['end_at'], 0, 10);
            $val['total_impressions'] = $pbInfo['total_impressions'];
            $val['competition'] = $pbInfo['total_impressions'] > 0 && $pbInfo['total_campaign_spend']['amount'] > 0 ? $pbInfo['total_campaign_spend']['currency_code'] . ' ' . round($pbInfo['total_campaign_spend']['amount'] / $pbInfo['total_impressions'] * 1000, 2) : $pbInfo['total_campaign_spend']['currency_code'] . ' ' . 0;
            $val['product_id'] = $pbInfo['products'][0]['product_id'];
            !empty($pbInfo['products'][0]['keywords']) && $val['keyword'] = join(',', $pbInfo['products'][0]['keywords']);
            $productInfo = L::sql("select 
                id,image,parentSku,sum(feed_impression) as feed_impression,sum(impressions) as impressions,sum(num_sold) as num_sold,min(date) as minDate,max(date) as maxDate 
            from (
                SELECT
                    a.id, a.`data`->>'$.image' as image,a.parentSku,b.feed_impression,b.impressions,b.num_sold,b.date
                FROM
                    `wish_product` a LEFT JOIN wish_product_stats b on a.id = b.id
                WHERE
                    a.`id` = '{$val['product_id']}'
                AND b.date >= '{$val['start_at']}'
                AND b.date <= '{$val['end_at']}'
                ORDER BY b.date desc
                LIMIT 7
            ) aa group by id,image,parentSku");
            if(empty($productInfo[0])){
                $productInfo = L::sql("select 
                    id,image,parentSku,sum(feed_impression) as feed_impression,sum(impressions) as impressions,sum(num_sold) as num_sold,min(date) as minDate,max(date) as maxDate 
                from (
                    SELECT
                        a.id, a.`data`->>'$.image' as image,a.parentSku,b.feed_impression,b.impressions,b.num_sold,b.date
                    FROM
                        `wish_product` a LEFT JOIN wish_product_stats b on a.id = b.id
                    WHERE
                        a.`id` = '{$val['product_id']}'
                    ORDER BY b.date desc
                    LIMIT 7
                ) aa group by id,image,parentSku");
            }
            $val['image'] = !empty($productInfo[0]['image']) ? $productInfo[0]['image'] : '-';
            $val['parentSku'] = !empty($productInfo[0]['parentSku']) ? $productInfo[0]['parentSku'] : '-';
            $val['minDate'] = !empty($productInfo[0]['minDate']) ? $productInfo[0]['minDate'] : '-';
            $val['maxDate'] = !empty($productInfo[0]['maxDate']) ? $productInfo[0]['maxDate'] : '-';
            $val['feed_impression'] = !empty($productInfo[0]['feed_impression']) ? $productInfo[0]['feed_impression'] : '0';
            $val['impressions'] = !empty($productInfo[0]['impressions']) ? $productInfo[0]['impressions'] : '0';
            $val['num_sold'] = !empty($productInfo[0]['num_sold']) ? $productInfo[0]['num_sold'] : '0';
            $val['mainMap'] = !empty($val['impressions']) ? round($val['feed_impression'] / $val['impressions']) . ':1' : '-';
            $val['buy'] = !empty($val['num_sold']) ? round($val['impressions'] / $val['num_sold']) . ':1' : '-';
            $orderInfo = L::sql("SELECT
                SUM( `profitsData` ->> '$.gross' ) AS gross,
                count( 0 ) AS qty 
            FROM
                `dxm_order` 
            WHERE
                `orderData` LIKE '%{$val['product_id']}%'
            AND CONVERT(`profitsData`->>'$.gross', DECIMAL(10,2)) > -10000");
            $val['orderGross'] = !empty($orderInfo[0]['gross']) && !empty($orderInfo[0]['qty']) ? round($orderInfo[0]['gross'] / $orderInfo[0]['qty'], 2) : '0';
            $val['orderQty'] = !empty($orderInfo[0]['qty']) ? $orderInfo[0]['qty'] : 0;
            $pbAmount = $pbInfo['total_campaign_spend']['currency_code'] == 'USD' ? $pbInfo['total_campaign_spend']['amount'] * 6.48 : $pbInfo['total_campaign_spend']['amount'];
            $val['pbGross'] = !empty($val['orderGross']) && !empty($val['sales']) ? round($val['orderGross'] - ($pbAmount / $val['sales']), 2) : 0;
        }
    }

}
return true;